import { defineComponent, reactive, toRefs, computed, h } from 'vue'
import VeDropdown from 'amtf/components/dropdown'
import VeIcon from 'amtf/components/icon'
import { ICON_NAMES } from 'amtf/constants'

import { use样式 } from 'amtf/hooks'
import {
  isEmptyValue,
  getValByUnit,
  拼组件名,
  isFunction,
  isBoolean,
  getRandomId,
} from 'amtf/utils'
const 主名 = 'table-header-filter-custom-content'
const 组件名 = 拼组件名(主名)

export default defineComponent({
  name: 组件名,
  props: {
    column: {
      type: Object,
      required: true,
    },
  },
  setup(props) {
    const { 拼样式名_table直属 } = use样式(主名)

    const state = reactive({
      internalVisible: false,
    })

    const updateVisibleBasedOnColumn = computed(() => {
      const column = props.column
      if (
        column.filterCustom &&
        isBoolean(column.filterCustom.defaultVisible)
      ) {
        return column.filterCustom.defaultVisible
      }
      return false
    })

    watch(
      () => props.column,
      (newColumn) => {
        state.internalVisible = updateVisibleBasedOnColumn.value
      },
      { immediate: true, deep: true }
    )

    const visibleChange = (visible) => {
      state.internalVisible = visible
    }

    const getCustomContent = (h) => {
      let result = null
      const { render } = props.column.filterCustom
      if (isFunction(render)) {
        const props = {
          slot: 'custom-content',
        }
        result = (
          <div {...props}>
            {render(
              {
                showFn: () => (state.internalVisible = true),
                closeFn: () => (state.internalVisible = false),
              },
              h
            )}
          </div>
        )
      }
      return result
    }

    const getIcon = (h) => {
      let result
      const { filterIcon } = props.column.filterCustom
      if (isFunction(filterIcon)) {
        result = filterIcon(h)
      } else {
        result = <VeIcon name={ICON_NAMES.FILTER} />
      }
      return result
    }

    const close = () => {
      state.internalVisible = false
    }

    const show = () => {
      state.internalVisible = true
    }

    return () => (
      <VeDropdown
        {...{
          isCustomContent: true,
          isControlled: true,
          visible: state.internalVisible,
          beforeVisibleChange: props.column.filterCustom.beforeVisibleChange,
        }}
        onDropdownVisibleChange={visibleChange}
      >
        {/* icon */}
        <span class={拼样式名_table直属('filter')}>
          <span class={拼样式名_table直属('filter-icon')}>{getIcon(h)}</span>
        </span>
        {/* custom content */}
        {getCustomContent(h)}
      </VeDropdown>
    )
  },
})
